const API_ENDPOINT = process.env.NEXT_PUBLIC_API_ENDPOINT;

// 全局图片加载器
export const myLoader = ({ src }: { src: string }) => {
  return `${process.env.NEXT_PUBLIC_API_ENDPOINT}/api/files/${src}`;
};

const fetchWithToken = async (url: string, options: RequestInit = {}) => {
  const token = localStorage.getItem('token');

  // 强制指定 headers 的类型为 Record<string, string>
  const headers: Record<string, string> = {
    ...options.headers as Record<string, string>,  // 强制转换 options.headers 为 Record<string, string>
  };

  if (token) {
    headers['Authorization'] = `Bearer ${token}`;
  }

  const response = await fetch(`${API_ENDPOINT}${url}`, {
    ...options,
    headers,
  });

  if (!response.ok) {
    const errorData = await response.json();
    throw new Error(errorData.message || '请求失败');
  }

  return response.json();
};


// 生成图片的函数
export const generateImage = async (prompt: string) => {
  return await fetchWithToken('/api/custom/hunyuan/generate', {
    method: 'POST',
    headers: {
      'Content-Type': 'application/json',
    },
    body: JSON.stringify({ prompt }),
  });
};

// 查询任务状态的函数
export const queryJobStatus = async (jobId: string) => {
  return await fetchWithToken(`/api/custom/hunyuan/query?jobId=${jobId}`);
};

// 保存到收藏的函数
export const saveToFavorites = async (formData: FormData) => {
  return await fetchWithToken('/api/collections/tatoo_history_pic/records', {
    method: 'POST',
    body: formData,
  });
};

// 查询收藏列表的函数
export const fetchFavorites = async (page: number, perPage: number) => {
  return await fetchWithToken(`/api/collections/tatoo_history_pic/records?sort=-created&page=${page}&perPage=${perPage}&filter=job_gpupic_id.by_user='5h5mfcaf8r8wjoa'&is_delete=false&expand=job_gpupic_id`);
};

// 提交sana任务的函数
export const generateSanaImage = async (prompt: string, sessionHash: string) => {
  return await fetchWithToken('/api/custom/sana/generate', {
    method: 'POST',
    headers: {
      'Content-Type': 'application/json',
    },
    body: JSON.stringify({ prompt, session_hash: sessionHash }),
  });
};

// 查询sana任务状态的函数
export const querySanaJobStatus = async (sessionHash: string) => {
  return await fetchWithToken(`/api/custom/sana/query?session_hash=${sessionHash}`);
};

export { fetchWithToken };

